package com.exam.test;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class AsyncExceptionHandling {
    private static final ConcurrentHashMap<Integer, Throwable> exceptions = new ConcurrentHashMap<>();

    public static void main(String[] args) throws InterruptedException {
      ExecutorService executor = Executors.newFixedThreadPool(3);
      long startTime = System.currentTimeMillis();
      // 提交任务到线程池
      for (int i = 0; i < 5; i++) {
        final int taskNumber = i;
        executor.submit(() -> {
          try {
            Thread.sleep(1000);
            if (taskNumber == 2) {
              throw new RuntimeException("Exception in task " + taskNumber);
            }
            System.out.println("Executing task " + taskNumber);
          } catch (Throwable e) {
            // 在这里捕获异常，并存储起来
            exceptions.put(taskNumber, e);
          }
        });
      }

      // 主线程可以在这里做其他事情，而不会阻塞
      // ...

      // 等待所有任务完成
      executor.shutdown();
      executor.awaitTermination(1, TimeUnit.MINUTES);
      long endTime = System.currentTimeMillis();
      System.out.println(endTime-startTime);
      // 检查是否有异常发生
      exceptions.forEach((taskId, exception) -> {
        System.out.println("Task " + taskId + " threw an exception: " + exception.getMessage());
      });
    }
}
